package handler

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"vid-man2/models"
	"vid-man2/pkg"
)

func Login(c *gin.Context) {
	uid := c.Query("uid")
	token, _ := pkg.TokenHandler(uid)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": token,
	})
}
func List(c *gin.Context) {
	//uid, _ := c.Get("uid")
	//c.JSON(200, gin.H{
	//	"code": 200,
	//	"msg":  "success",
	//	"uid":  uid,
	//})
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var count int64
	models.DB.Model(&models.Video{}).Count(&count)

	var video []models.Video
	err := models.DB.Offset(offset).Limit(size).Find(&video).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"video": video,
		},
	})
	return

}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	if title == "" || content == "" || img == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}
	video := models.Video{
		Title:   title,
		Content: content,
		Img:     img,
	}
	err := models.DB.Create(&video).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var video models.Video
	err := models.DB.Where("id =?", id).First(&video).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": video,
	})
	return
}
